import set_storage_sync from '@dfeidao/atom-wxapp/api/cache/set';
import hide_toast from '@dfeidao/atom-wxapp/api/interaction/hide-toast';
import show_toast from '@dfeidao/atom-wxapp/api/interaction/show-toast';
import redirect_to from '@dfeidao/atom-wxapp/api/navigation/redirect-to';
import { post } from '@dfeidao/atom-wxapp/api/network/request';
import set_global from '@dfeidao/atom-wxapp/global/set';
import { IFeidaoAiWeappPage } from '@dfeidao/atom-wxapp/interfaces';
import get_local from '@dfeidao/atom-wxapp/local/get';
import render from '@dfeidao/atom-wxapp/render/render';
import { login } from '../atom/config';

interface IUserInfo {
	_id: string;
	usercode: string;
	user_name: string;
	name_spell: string;
	is_disabled: boolean;
	create_time: number;
	productid: string;
	avatar_path: string;
	avatar_name: string;
	avatar_type: string;
	email: string;
	phone: string;
	last_login_time: number;
	phone_verified: boolean;
	email_verified: boolean;
	is_admin: boolean;
	code: number;
	msg: string;
	sessionID: string;
}

export default async function a003(fd: IFeidaoAiWeappPage) {
	render(fd, { login_loading: true });
	const userName = get_local(fd, 'userName') as string;
	const userPwd = get_local(fd, 'userPwd') as string;

	if (!userName) {
		show_toast('账号不能为空', 'none', 1000);
		render(fd, { login_loading: false });
	} else if (!userPwd) {
		show_toast('密码不能为空', 'none', 1000);
		render(fd, { login_loading: false });
	} else {
		const data = JSON.stringify({
			userName,
			userPwd
		});
		const res = await post(login, data) as { data: IUserInfo };
		const userinfo = res.data;
		console.log(userinfo, '11111111111111');

		setTimeout(() => {
			if (userinfo.usercode) {
				console.log(userinfo);
				// 将userinfo存到本地
				set_global('userinfo', userinfo);
				set_storage_sync('user', {
					userName,
					userPwd
				});

				redirect_to('../main/main');
			} else {
				show_toast(userinfo.msg, 'none');
				setTimeout(() => {
					hide_toast();
				}, 2000);
			}
			render(fd, { login_loading: false });
		}, 1000);
	}
}
